import { Module } from 'vuex'
import { ITagState } from './type'
import { IRootState } from '../type'
import { RouteLocationNormalized } from 'vue-router'
import { routeLocation2FlatObj } from '@/utils/route-utils'
import { localCache } from '@/utils/cache'

const tagModule: Module<ITagState, IRootState> = {
  namespaced: true,
  state() {
    return {
      cachedList: [], // 组件名称字符串构成的数组
      routeLocations: [], // RouteLocationNormalized 类型的对象构成的数组
      routeFlat: []
    }
  },
  mutations: {
    changeCachedList(state, routeLocation: RouteLocationNormalized) {
      const routeName: string = routeLocation.name?.toString() || ''
      if (!routeName || routeName.length <= 0) return

      const routeFlat = routeLocation2FlatObj(routeLocation)
      if (!state.cachedList || state.cachedList.length <= 0) {
        state.routeFlat = []

        state.cachedList.push(routeName)
        state.routeFlat.push(routeFlat)
        // state.routeLocations.push(routeLocation)

        localCache.setCache('cachedList', state.cachedList)
        localCache.setCache('routeFlat', state.routeFlat)

        return
      }

      const route = state.cachedList.some(
        (currentRouteName) => currentRouteName === routeName
      )
      if (!route) {
        state.cachedList.push(routeName)
        // state.routeLocations.push(routeLocation)
        state.routeFlat.push(routeFlat)

        localCache.setCache('cachedList', state.cachedList)
        localCache.setCache('routeFlat', state.routeFlat)
      }
    },

    updateState(state, { c1, c2 }) {
      state.cachedList = c1
      state.routeFlat = c2
    }
  },
  actions: {
    updateStateAction({ commit }, routeLocation: RouteLocationNormalized) {
      commit('changeCachedList', routeLocation)
    },
    loadLocalAction({ commit }) {
      const c1 = localCache.getCache('cachedList') || []
      const c2 = localCache.getCache('routeFlat') || []

      commit('updateState', { c1, c2 })
    }
  }
}

export { tagModule }
